// pages/optional/analyse/index.js
const {
  schoolList,
  twoMajorList,
  majorPageList,
  matchSpecial,
  matchSchool,
  majorList,
  schoolReportAdd,
  schoolReportEdit,
  schoolReportList
} = require('../../../api/api')
const {
  checkLogin,
  filterObj
} = require('../../../utils/util')
const selectorSchoolDatas = [{
    id: 0,
    title: "全国",
    type: "radiobox",
    key: "province",
    items: []
  },
  {
    id: 1,
    title: "专业",
    type: "checkbox",
    key: "major",
    items: []
  },
  {
    id: 3,
    title: "排序",
    key: "orderBy",
    type: 'radiobox',
    items: [{
        id: 0,
        title: "默认排序",
        checked: true
      }, {
        id: 'scoreDesc',
        title: "分数由高到低",
      },
      {
        id: 'scoreAsc',
        title: "分数由低到高",
      },
      {
        id: 'hotDesc',
        title: "热度由高到低",
      },
      {
        id: 'workRateDesc',
        title: "就业率由高到低",
      },
      {
        id: 'upRateDesc',
        title: "国内升学率由高到底",
      },
    ],
  },
  {
    id: 4,
    title: "其他",
    key: "batch",
    type: 'other',
    items: [],
  },


]
const filterBatch = [{
    id: 3,
    title: "办学层次",
    key: "eduLevelName",
    type: 'radiobox',
    items: [{
        id: '本科',
        title: "本科",
        checked: true
      }, {
        id: '专科（高职）',
        title: "专科（高职）",
      },

    ],
  },
  {
    id: 3,
    title: "办学类型",
    key: "eduType",
    type: 'checkbox',
    items: [{
        id: '公办学校',
        title: "公办学校",
        checked: true
      }, {
        id: '民办学校',
        title: "民办学校",
      },
      {
        id: '中外合作办学',
        title: "中外合作办学",
      },
      {
        id: '内地港澳台合作办学',
        title: "内地港澳台合作办学",
      },
    ],
  },
  {
    id: 3,
    title: "院校特色",
    key: "schoolLabel",
    type: 'checkbox',
    items: [{
        id: 985,
        title: "985",
      }, {
        id: 211,
        title: "211",
      },
      {
        id: '双一流',
        title: "双一流",
      },
      {
        id: '强基计划',
        title: "强基计划",
      },
    ],
  },
  {
    id: 4,
    title: "院校类型",
    key: "schoolType",
    type: 'checkbox',
    items: [{
        id: '综合类',
        title: "综合类",
      }, {
        id: '理工类',
        title: "理工类",
      },
      {
        id: '农林类',
        title: "农林类",
      },
      {
        id: '医药类',
        title: "医药类",
      },
      {
        id: '师范类',
        title: "师范类",
      },
    ],
  },
]


const selectorMajorDatas = [{
    id: 0,
    title: "不限",
    key: "level1Name",
    type: 'radiobox',
    items: [{
        id: '',
        title: "不限",
        checked: true
      },
      {
        id: '本科',
        title: "本科",
      }, {
        id: '专科（高职）',
        title: "专科（高职）",
      }
    ],
  },
  {
    id: 1,
    title: "专业类别",
    key: "category",
    type: 'radiobox',
    items: [],
  },
  // {
  //   id: 2,
  //   title: "专业排序",
  //   key: "orderDesc",
  //   type: 'radiobox',
  //   items: [{
  //       id: 'hotDesc',
  //       title: "专业热度由高到底",
  //       checked: true
  //     }, {
  //       id: 'spCode',
  //       title: "专业代码排序",
  //     },
  //     {
  //       id: 'salaryDesc',
  //       title: "平均薪酬由高到低",
  //       icon: '/images/my/vip.png',
  //       width: '60rpx',
  //       height: '26rpx'
  //     },
  //     {
  //       id: 'boyDesc',
  //       title: "男生比例由高到低",
  //     },
  //     {
  //       id: 'girlDesc',
  //       title: "女生比例由高到底",
  //     },
  //   ],
  // },
]


function filterArr(selected, selectData) {
  let c = selectData.filter((item) => {
    return (selected.indexOf(item.id) > -1)
  })
  return c
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bottomLift: getApp().globalData.bottomLift,
    chooseList: [],
    schoolTotal: 0,
    specialTotal: 0,
    pageTNo: 1,
    pageTSize: 20,
    score: '',
    tabIndex: 0,
    list: [],
    isAnalyse: false,
    visible: false,
    mode: 'major',
    title: '',
    content: '',
    subjectData: [{
      id: 1,
      value: '智能排序'
    }, {
      id: 2,
      value: '志愿表导出'
    }, {
      id: 3,
      value: '智能填充'
    }],
    filterRouteKey: 'analyseFilters',
    selectedData: {
      province: 0,
      batch: 1,
      major: [],
      orderBy: 0,
      eduLevelName: 0,
      eduType: [],
      schoolLabel: [],
      schoolType: [],
      category: 0, //查询专业一级
      categoryId: 0, //查询专业二级id
      orderDesc: 'hotDesc',
      level1Name: '',
      selectedMajorList: []
    },
    selectorDataList: selectorSchoolDatas,
    filterBatch: filterBatch,
    schoolPageNo: 1,
    majorPageNO: 1,
    pageSize: 20,
    categoryFilter: {
      id: 1,
      title: "专业类别",
      key: "category",
      type: 'other',
      items: []
    },
    categoryList: [],
    setting: {
      height: '100rpx'
    },
    schoolList: [],
    majorList: [],
    cityList: [],
    matchProps: {
      schoolName: 'schoolName',
      schoolId: 'schoolId',
      majorNum: 'openMajor',
      schoolNum: 'openSchool',
      specialName: 'specialName',
      spname: 'level3Name'
    },
    optionalData: {},
    loader: false,
    selectorMajorList: [],
    optionalTotal: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getOptionalTotal()
    getApp().watch(this.callBack)
    if (options.params) {
      const params = JSON.parse(decodeURIComponent(options.params))
      const chooseList = params.subjects.split(',')
      const optionalData = {
        province: params.provinceId,
        year: params.year
      }
      this.setData({
        ...params,
        chooseList,
        optionalData
      })
    } else {
      this.setData({
        optionalData: wx.getStorageSync('optionalChooseFilters')
      })
    }
    const {
      filterRouteKey,
      selectedData
    } = this.data
    wx.setStorageSync(filterRouteKey, selectedData)
    this.getMajorPageList()
    this.onLoadFunc()
    this.fetchCity()
    this.fetchCategory()

  },
  async getOptionalTotal() {
    const params = {
      pageNo: 1,
      pageSize: 1
    }
    const {
      result
    } = await schoolReportList(params)
    this.setData({
      optionalTotal: result.total,
    })
  },
  callBack: function (val) {
    this.setData({
      loader: val
    })
  },
  onUnload() {
    const {
      filterRouteKey,
    } = this.data
    wx.removeStorageSync(filterRouteKey)
  },

  async fetchCategory() {
    const {
      selectorDataList,
      filterRouteKey
    } = this.data
    let selectedData = wx.getStorageSync(filterRouteKey)
    const params = {
      level1Name: selectedData.level1Name
    }
    const {
      result
    } = await twoMajorList(params)
    const categoryList = result.map((item) => {
      const children = item.children.map((child) => {
        return {
          title: child.name,
          id: child.name
        }
      })
      // children.unshift({
      //   id: 0,
      //   title: '不限'
      // })
      return {
        id: item.name,
        title: item.name,
        children
      };
    })
    // selectorDataList[1].items=categoryList
    categoryList.unshift({
      id: 0,
      title: '全部',
      children: [{
        id: 0,
        title: '不限'
      }]
    })
    this.setData({
      categoryList,
    })
    selectedData.category = 0
    selectedData.categoryId = 0
    this.setData({
      selectedData,
      selectorDataList
    })
    wx.setStorageSync(filterRouteKey, selectedData)
    this.filterKeyFunc()
  },
  async fetchCity() {
    const {
      filterBatch,
      selectorDataList
    } = this.data
    const eduTypeList = wx.getStorageSync('edu_type') || await getApp().getDictData('edu_type')
    const schoolLabelList = wx.getStorageSync('school_label') || await getApp().getDictData('school_label')
    const schoolTypeList = wx.getStorageSync('school_type') || await getApp().getDictData('school_type')
    const cityList = wx.getStorageSync('cityList') || await getApp().getCityList()
    cityList.unshift({
      id: 0,
      title: '全国',
      checked: true
    })
    selectorDataList[0].items = cityList
    filterBatch[1].items = eduTypeList
    filterBatch[2].items = schoolLabelList
    filterBatch[3].items = schoolTypeList
    this.setData({
      filterBatch,
      selectorDataList,
      cityList
    })
  },
  scroll() {
    const {
      selectorDataList,
      pageTSize
    } = this.data
    const count = selectorDataList[1].items.length - 1
    if (selectorDataList[1].items[count].length < pageTSize) {
      return
    }

    this.getMajorPageList(true)
  },
  searchMaj(e) {
    const {
      name
    } = e.detail
    const {
      selectorDataList
    } = this.data
    selectorDataList[1].items = []
    this.setData({
      name,
      pageTNo: 1,
      selectorDataList
    })
    this.getMajorPageList(true)
  },
  async getMajorPageList(flag) {
    const {
      pageTNo,
      pageTSize,
      name,
      selectorDataList,
    } = this.data
    let params = {
      name,
      pageNo: pageTNo,
      pageSize: pageTSize,
    }
    params = filterObj(params)
    const {
      result
    } = await majorPageList(params)

    result.records = result.records.map(e => {
      return {
        id: e.specialId,
        title: e.name,
        desc: e.level1Name + '-' + e.level2Name + '-' + e.level3Name,
      }
    })
    selectorDataList[1].items = selectorDataList[1].items.concat(result.records)
    if (result.records.length == 0) {
      return
    }
    this.setData({
      selectorDataList,
      selectorMajorList: this.data.selectorMajorList.concat(result.records),
      pageTNo: pageTNo + 1,
    })
    if (flag !== undefined) {
      this.selectComponent("#selector").syncData1(selectorDataList);
    }

  },
  //修改筛选条件--执行onloadFunc
  filterKeyFunc() {
    const {
      filterRouteKey,
      selectorDataList
    } = this.data
    const selectedData = wx.getStorageSync(filterRouteKey)
    let {
      category,
      categoryId,
      level1Name,
      orderDesc
    } = selectedData
    selectorDataList.map((item) => {
      const c = item.items.filter((child) => {
        return child.id == selectedData[item.key]
      })
      // item.title = (item.key == 'province') ? c.length > 0 ? c[0].title : item.title : item.title
      const isCategory = item.key == 'category'
      item.title = isCategory ? (categoryId && categoryId!=0 ? (categoryId || item.title) : category ? (category || item.title) : '专业类型') : item.key == 'level1Name' && !level1Name ? '专业层级' : item.key == 'orderDesc' && orderDesc == 'hotDesc' ? '专业排序' : (item.key == 'province' || item.key == 'level1Name') ? c.length > 0 ? c[0].title : item.title : item.title
      return item
    })


    this.setData({
      selectorDataList,
      selectedData
    })

    this.filterMajor()

  },

  //修改专业--执行onloadFunc
  filterMajor() {
    const {
      filterRouteKey
    } = this.data
    const selectedMajorList = wx.getStorageSync(filterRouteKey).selectedMajorList
    this.setData({
      selectedMajorList
    })
    checkLogin().then((res) => {
      this.onLoadFunc(this.data.tabIndex)
    })
  },
  async onSelectChangedRoute(e) {

    const {
      filterRouteKey
    } = this.data
    wx.setStorageSync(filterRouteKey, {
      ...e.detail
    });
    if (this.data.selectedData.level1Name !== e.detail.level1Name) {
      this.fetchCategory()
      return
    }
    this.filterKeyFunc()
  },
  onLoadFunc(tabIndex) {
    if (tabIndex !== undefined) {
      if (tabIndex == 0) {
        this.setData({
          schoolPageNo: 1,
          schoolList: [],
        })
        this.getSchoolList()
      } else {
        this.setData({
          majorPageNO: 1,
          majorList: []
        })
        this.getMajorList()
      }
      return
    }
    this.setData({
      schoolPageNo: 1,
      majorPageNO: 1,
      schoolList: [],
      majorList: []
    })
    this.getMajorList()
  },

  async getSchoolList() {
    getApp().globalData.loader = true
    const {
      schoolPageNo,
      pageSize,
      optionalData,
      firstSelect,
      filterRouteKey,
      subjects,
      provinceId
    } = this.data
    let {
      province,
      schoolType,
      eduType,
      major,
      orderBy,
      schoolLabel,
      eduLevelName
    } = wx.getStorageSync(filterRouteKey)
    eduType = eduType.join(',')
    schoolType = schoolType.join(',')
    let params = {
      pageNo: schoolPageNo,
      eduType,
      schoolType,
      pageSize,
      orderBy,
      specialtyIds: major,
      subjects,
      eduLevelName,
      schoolProvinceId: province,
      type: firstSelect,
      provinceId: optionalData.province,
      year: optionalData.year,
    }
    let obj = wx.getStorageSync('school_label_obj')
    let newObj = {}
    schoolLabel.map(e => {
      if (obj[e]) {
        newObj[obj[e]] = 1
      }
    })
    params = Object.assign(newObj, params)
    params = filterObj(params)
    const {
      result
    } = await matchSchool(params)
    this.setData({
      loader: false
    })
    if (result.records.length == 0) {
      return
    }
    result.records.map((item) => {
      let array = []
      if (item.isProject985 === 1) {
        array.push('985')
      }
      if (item.isProject211 === 1) {
        array.push('211')
      }
      if (item.isDoubleTop === 1) {
        array.push('双一流')
      }
      if (item.isEducationDept > 0) {
        array.push('教育部')
      }
      array.push('一流建设学科')
      item['filter'] = array
    })

    this.setData({
      ['schoolList[' + (schoolPageNo - 1) + ']']: result.records,
      schoolPageNo: schoolPageNo + 1,
      schoolTotal: result.total,
    })
  },
  async getMajorList() {
    getApp().globalData.loader = true
    const {
      majorPageNO,
      pageSize,
      optionalData,
      firstSelect,
      subjects
    } = this.data
    const {
      orderDesc,
      category,
      categoryId,
      level1Name
    } = wx.getStorageSync(this.data.filterRouteKey)
    let params = {
      level1Name,
      level2Name: category,
      level3Name: categoryId,
      orderBy: orderDesc,
      pageNo: majorPageNO,
      pageSize,
      subjects,
      type: firstSelect,
      provinceId: optionalData.province,
      year: optionalData.year,
    }
    params = filterObj(params)
    const {
      result
    } = await matchSpecial(params)
    this.setData({
      loader: false
    })
    result.records.map((item) => {
      if (item.spname.indexOf('（') > -1) {
        const index = item.spname.indexOf('（')
        item['specialName'] = item.spname.substring(0, index)
      } else {
        item['specialName'] = item.spname
      }
    })
    this.setData({
      ['majorList[' + (majorPageNO - 1) + ']']: result.records,
      majorPageNO: majorPageNO + 1,
      specialTotal: result.total,
    })
  },

  changeIndex(e) {
    const {
      index,
      type,
    } = e.currentTarget.dataset
    var {
      cityList,
      majorList,
      schoolList,
      selectorMajorList
    } = this.data
    this.setData({
      [type]: parseInt(index),
    })
    if (index == 0) {
      var list = selectorSchoolDatas
      list[0].items = cityList
      list[1].items = selectorMajorList
      this.setData({
        selectorDataList: list,
      })
      if (schoolList.length > 0) return
      this.setData({
        schoolPageNO: 1
      })
      this.getSchoolList()
      this.filterMajor()
    } else {
      const list = JSON.stringify(selectorMajorDatas)
      this.setData({
        selectorDataList: JSON.parse(list),
        // selectorDataList:selectorMajorDatas
      })
      if (majorList.length > 0) return
      this.setData({
        majorPageNO: 1
      })
      this.getMajorList()

    }
  },
  onReachBottom() {
    const {
      majorList,
      schoolList,
      pageSize,
      tabIndex
    } = this.data
    if (tabIndex == 0) {
      let count = schoolList.length - 1
      if (schoolList[count].length < pageSize) {
        return
      }
      this.getSchoolList()
    } else {
      let count = majorList.length - 1
      if (majorList[count].length < pageSize) {
        return
      }
      this.getMajorList()
    }


  },
  toggle(e) {
    const {
      type,
      value
    } = e.currentTarget.dataset
    const {
      subjects,
      firstSelect
    } = this.data
    value['subjects'] = subjects.split(',')
    value['type'] = firstSelect
    this.setData({
      mode: type,
      visible: true,
      checkedValue: value
    })
  },
  goto(e) {
    const {
      url
    } = e.currentTarget.dataset
    wx.navigateTo({
      url,
    })
  },
  async saveSubject() {
    const {
      firstSelect,
      secondSelect,
      optionalData,
      provinceId,
      province,
      planMatchId
    } = this.data
    //自主选科
    const params = {
      firstSelect, //首选科目
      provinceId, //城市id
      province, //城市名称
      subjects: secondSelect.split(','), //科目
      year: optionalData.year,
      type: 'custom'
    }
    if (planMatchId) {
      params.id = planMatchId
      const {
        result
      } = await schoolReportEdit(params)
    } else {
      const {
        result
      } = await schoolReportAdd(params)
      wx.showToast({
        title: '保存成功',
        icon: 'none'
      })
      this.getOptionalTotal()
    }


  },
  onShareAppMessage() {
    return {
      title: '新高考选科工具',
      imageUrl:'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/shareImg.jpg',
      path:'/pages/optional/index/index'
    }
  }
})